﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Windows.Controls;
using System.Xml.Linq;

namespace SilverlightChartDisplay
{
    public partial class Page : UserControl
    {
        

        public Page(string elementId)
        {
            
            InitializeComponent();
            // "Paris_75_1633794099529012890_Cafe expresso"
            
            this.LoadData(elementId);
        }

        private void LoadData(string elementId)
        {
            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            Uri uri = new Uri(client.BaseAddress);
            string serviceAdress = uri.Host + ":" + uri.Port;
            client.OpenReadAsync(new Uri(string.Format("http://{0}/Resto55Service.svc/element?id={1}", serviceAdress, elementId)));
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Dictionary<DateTime, double> values = new Dictionary<DateTime, double>();
            NumberFormatInfo numberFormat = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat;
            string decimalSeparator = numberFormat.NumberDecimalSeparator;

            XDocument xdoc = XDocument.Load(e.Result);
            var elements = xdoc.Elements().First().Descendants();
            foreach (XElement el in elements)
            {
                double prix = 0;
                DateTime date = DateTime.MinValue;
                foreach (XElement child in el.Descendants())
                {

                    if (child.Name.LocalName.Equals("prix"))
                    {
                        string _price = child.Value.Replace(".", decimalSeparator).Replace(",", decimalSeparator);
                        prix = double.Parse(_price, numberFormat);
                    }

                    if (child.Name.LocalName.Equals("dateSaisie"))
                    {
                        string _date = child.Value;
                        date = DateTime.Parse(_date);
                    }
                }
                if (date.CompareTo(DateTime.MinValue) != 0)
                    values.Add(date, prix);
            }

            CreateChart(values);
        }

        private void CreateChart(Dictionary<DateTime, double> values)
        {
            chart.DataContext = values;
        }
    }
}
